/**
 * 发票查验服务 / 发票识别服务
 */
import React, { Component } from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import { messages } from "share/common"
import { Popover, Badge, Button, message } from 'antd'
import errorMessage from 'share/errorMessage'
import moment from 'moment'
import TableList from '../table-list'
import requestAndExpenseService from '../request-and-expense-settings.service'

class InvoiceInspection extends Component {

  state = {
    enableLoading: false,
    disableLoading: false,
    selectedRowKeys: [],
    serviceTypeCode: this.props.serviceTypeCode,
    isAll: false, //是否全选
    legalEntityIds: [], //全选时反选的数据
    totalCount: 0,
  };

  infoData = {
    dataSource: { explain: messages('expense-2.key4')/*您可在此页面为（抬头）法人 开通/关闭 增值服务，增值服务订单付款后默认所有（抬头）法人下的员工可用此增值服务。*/ },
    attributes: [{ title: messages('expense-2.key5')/*说明*/, dataIndex: 'explain', span: 24 }],
    more: (
      <a onClick={() => this.toOrderPage()} style={{ display: 'block', textAlign: 'right', marginTop: 12 }}>
        {messages('expense-2.key6')/*去下单*/} >>
      </a>
    ),
  };

  toOrderPage = () => {
    const { serviceTypeCode } = this.state;
    let url = menuRoute.getRouteItem('order-management').url;
    this.context.router.push(url.replace(':orderType', serviceTypeCode))
  };

  searchForm = [{
    id: 'legalEntityName',
    dataIndex: 'legalEntityName',
    label: messages('expense-2.key7')/*（抬头）法人名称*/,
    component: 'Input'
  }];

  columns = [{
    title: messages('expense-2.key7')/*（抬头）法人名称*/,
    dataIndex: 'legalEntityName',
    render: value => (
      value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    )
  }, {
    title: messages('expense-2.key8')/*纳税人识别号*/,
    dataIndex: 'taxpayerNumber',
    render: value => (
      value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    )
  }, {
    title: messages('expense-2.key9')/*相关订单*/,
    dataIndex: 'orderCode',
    render: value => (
      value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    )
  }, {
    title: messages('expense-2.key10')/*开通日期*/,
    dataIndex: 'effectiveDate',
    render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
  }, {
    title: messages('expense-2.key11')/*到期日期*/,
    dataIndex: 'expireDate',
    render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
  }, {
    title: messages('common.column.status')/*状态*/,
    dataIndex: 'status',
    width: '10%',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('expense-2.key12')/*启用temp*/ : messages('expense-2.key13')/*禁用temp*/}
      />
    )
  }];

  componentWillReceiveProps(nextPros) {
    this.setState({
      isAll: false,
      totalCount: 0,
      legalEntityIds: [],
      selectedRowKeys: [],
      serviceTypeCode: nextPros.serviceTypeCode
    }, () => {
      this.advancedTableRef.setFieldsValue(null, true);
    })
  }

  service = (page, size, searchParams, extraParams) => {
    let params = {
      page,
      size,
      ...searchParams,
      ...extraParams
    };
    return requestAndExpenseService.getLegalEntities(params);
  };

  //修改状态
  changeStatus = type => {
    const { selectedRowKeys, serviceTypeCode, legalEntityIds, isAll } = this.state;
    let serviceType = type === 'enable' ? 'batchOpenLegalEntity' : 'batchCloseLegalEntity';
    this.setState({ [`${type}Loading`]: true });
    requestAndExpenseService[serviceType](
      serviceTypeCode,
      isAll,
      isAll ? legalEntityIds : selectedRowKeys
    ).then(res => {
      this.setState({ [`${type}Loading`]: false });
      this.advancedTableRef.getList();
      message.success(res.data.msg || messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      this.setState({ [`${type}Loading`]: false });
      errorMessage(e.response);
    })
  };

  handleRecordSelect = (record, selected) => {
    let { legalEntityIds, selectedRowKeys } = this.state;
    if (selected) {
      legalEntityIds.delete(record.legalEntityId);
      selectedRowKeys.push(record.legalEntityId);
    } else {
      legalEntityIds.push(record.legalEntityId);
      selectedRowKeys.delete(record.legalEntityId);
    }
    this.setState({ legalEntityIds, selectedRowKeys })
  };

  handleSelectAll = (selected, selectedRows, changeRows) => {
    let { legalEntityIds, selectedRowKeys } = this.state;
    if (selected) {
      changeRows.map(item => {
        legalEntityIds.delete(item.legalEntityId);
        selectedRowKeys.push(item.legalEntityId)
      })
    } else {
      changeRows.map(item => {
        legalEntityIds.push(item.legalEntityId);
        selectedRowKeys.delete(item.legalEntityId)
      })
    }
    this.setState({ legalEntityIds, selectedRowKeys })
  };

  onGetData = (data, { total }) => {
    let { isAll, legalEntityIds, selectedRowKeys } = this.state;
    isAll && data.map(item => {
      if (!~legalEntityIds.indexOf(item.legalEntityId) && !~selectedRowKeys.indexOf(item.legalEntityId)) {
        selectedRowKeys.push(item.legalEntityId)
      }
    });
    this.setState({ selectedRowKeys, totalCount: total })
  };

  render() {
    const {
      selectedRowKeys, enableLoading, disableLoading, serviceTypeCode, totalCount, legalEntityIds, isAll
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      hideDefaultSelections: true,
      selections: [{
        key: 'data-all',
        text: messages('expense-2.key14')/*全选全部*/,
        onSelect: value =>this.setState({ selectedRowKeys: value, legalEntityIds: [], isAll: true })
      }, {
        key: 'page-all',
        text: messages('expense-2.key15')/*全选当页*/,
        onSelect: value => this.setState({ selectedRowKeys: value, legalEntityIds: [], isAll: false })
      }],
      onSelect: this.handleRecordSelect,
      onSelectAll: this.handleSelectAll,
    };
    return (
      <div style={{ height: 'calc(100% - 64px)' }}>
        <TableList
          infoData={this.infoData}
          tableParams={{
            tableName: `invoice-check-setting-table.${serviceTypeCode}`,
            rowKey: "legalEntityId",
            searchForm: this.searchForm,
            columns: this.columns,
            rowSelection,
            extraParams: { serviceTypeCode },
            service: this.service,
            onGetData: this.onGetData,
            onRef: ref => this.advancedTableRef = ref,
            footer: (
              <div>
                {['enable', 'disable'].map(type => (
                  <Button
                    type="primary"
                    disabled={!selectedRowKeys.length}
                    loading={type === 'enable' ? enableLoading : disableLoading}
                    style={{ marginRight: 10 }}
                    onClick={() => this.changeStatus(type)}
                  >
                    {messages(`common.status.${type}`)}
                  </Button>
                ))}
              </div>
            ),
            renderSelectedNumber: () => (
              <span>
              {messages('expense-2.key16')/*已选择*/}
                <span className='advanced-table-footer-selected-number'>
                {isAll ? totalCount - legalEntityIds.length : selectedRowKeys.length}
              </span>
                {messages('expense-2.key17')/*条*/}
            </span>
            )
          }}
        />
      </div>
    )
  }
}

InvoiceInspection.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(InvoiceInspection)
